package cn.iocoder.yudao.module.cmt.service.course;

import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
import cn.iocoder.yudao.module.cmt.controller.admin.course.vo.*;
import cn.iocoder.yudao.module.cmt.dal.dataobject.course.CourseInfoDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.cmt.dal.mysql.course.CourseInfoMapper;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.cmt.enums.ErrorCodeConstants.*;

@Service
@Validated
public class CourseInfoServiceImpl implements CourseInfoService {

    @Resource
    private CourseInfoMapper courseInfoMapper;

    @Override
    public Long createCourseInfo(CourseInfoSaveReqVO createReqVO) {
        CourseInfoDO courseInfo = BeanUtils.toBean(createReqVO, CourseInfoDO.class);
        courseInfoMapper.insert(courseInfo);
        return courseInfo.getId();
    }

    @Override
    public void updateCourseInfo(CourseInfoSaveReqVO updateReqVO) {
        validateCourseInfoExists(updateReqVO.getId());
        CourseInfoDO updateObj = BeanUtils.toBean(updateReqVO, CourseInfoDO.class);
        courseInfoMapper.updateById(updateObj);
    }

    @Override
    public void deleteCourseInfo(Long id) {
        validateCourseInfoExists(id);
        courseInfoMapper.deleteById(id);
    }

    private void validateCourseInfoExists(Long id) {
        if (courseInfoMapper.selectById(id) == null) {
            throw exception(COURSE_INFO_NOT_EXISTS);
        }
    }

    @Override
    public CourseInfoDO getCourseInfo(Long id) {
        return courseInfoMapper.selectById(id);
    }

    @Override
    public PageResult<CourseInfoDO> getCourseInfoPage(CourseInfoPageReqVO pageReqVO) {
        return courseInfoMapper.selectPage(pageReqVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteCourseInfoListByIds(List<Long> ids) {
        ids.forEach(this::validateCourseInfoExists);
        courseInfoMapper.deleteBatchIds(ids);
    }

}
